import { combineReducers } from 'redux';
import { Actions } from '../../../core/utils/IConstant';

function selectedTabIndexReducer(state = 0, action)
{
    switch(action.type)
    {
    case Actions.SCENIC.LIST.SET_SELECTED_TAB_INDEX:
        return action.index;
    case Actions.SCENIC.LIST.GO_BACK:
        return 0;
    default:
        return state;
    }
}

function keywordReducer(state = '', action)
{
    switch(action.type)
    {
    case Actions.SCENIC.LIST.SET_KEYWORD:
        return action.keyword;
    case Actions.SCENIC.LIST.GO_BACK:
        return '';
    default:
        return state;
    }
}

function groupReducer(state = {}, action)
{
    // 可能是我的周边列表/景区周边列表
    if(action.extraParams && action.extraParams.storeKey && action.extraParams.storeKey.length > 0)
    {
        return {...state};
    }
    let obj = state[action.orderFiled];
    obj = obj ? obj : {};
    switch(action.type)
    {
    case Actions.SCENIC.LIST.GET_LIST_REQUEST:
        return {
            ...state, 
            [action.orderFiled]: {
                ...obj,
                isFetching: true,
                pageIndex: action.pageIndex,
                keyword: action.keyword,
            }
        };
    case Actions.SCENIC.LIST.GET_LIST_SUCCESS:
        let dataList = action.pageIndex === 0 ? [] : obj.dataList;
        dataList = dataList ? dataList : [];
        if(action.result.results)
        {
            dataList = dataList.concat(action.result.results);
        }
        return {
            ...state,
            [action.orderFiled]: {
                ...obj,
                isFetching: false,
                dataList: dataList,
                total: action.result.total,
                pageIndex: action.pageIndex,
                keyword: action.keyword,
                hasMore: (action.result.total > dataList.length)
            }
        };
    case Actions.SCENIC.LIST.GET_LIST_FAILURE:
        return {
            ...state,
            [action.orderFiled]: {
                ...obj,
                isFetching: false,
            }
        };
    case Actions.SCENIC.LIST.GO_BACK:
        return {};
    case Actions.SCENIC.LIST.DELETE:
        return {
            ...state,
            [action.orderFiled]: {
                isFetching: false,
                dataList: [],
            }
        };
    case Actions.SCENIC.LIST.SET_LISTVIEW_OFFSET:
        return {
            ...state, 
            [action.orderFiled]: {
                ...obj,
                listViewOffset: action.listViewOffset
            }
        };
    default:
        return state;
    }
}

const listReducer = combineReducers({
    selectedTabIndex: selectedTabIndexReducer,
    keyword: keywordReducer,
    groups: groupReducer,
});

export default listReducer;